<?
$apache2_siteconf = "/etc/apache2/sites-available/default";
$shareDir = "/var/shares/";

function savebase() {
	global $apache2_siteconf;
	global $shareDir;

	$str_conf = file_get_contents($apache2_siteconf);
	if( preg_match('/\s*documentroot\s*([^\s]*)\s*/i', $str_conf , $match) < 1 ) {
		// Kunde ej hitta gamla docroot
		error('read_conf');
	}
    // Katalog för hemsida är angiven, ställ in och aktivera
	else if( isset($_POST['directory']) ) {
		$old_directory = $match[1];

		//$serveradm = $_POST['serveradm'];
		//$servername = $_POST['servername'];
		$directory = $_POST['directory'];
		$count = 0;

		/*
		if( $serveradm != "" ) {
			$str_conf = preg_replace('/(\s*serveradmin\s*)([^\s]*)/i', "$1$serveradm", $str_conf, 1, $count);
			if( $count == 0 )
				$str_conf = preg_replace('/(<virtualhost \*>\s*)/i', "$1ServerAdmin $serveradm\n", $str_conf);
		}
		else
			$str_conf = preg_replace('/(\s*serveradmin\s*.*)/i', "", $str_conf, 1, $count);

		if( $servername != "" ) {
			$str_conf = preg_replace('/(\s*servername\s*)([^\s]*)/i', "$1$servername", $str_conf, 1, $count);
			if( $count == 0 )
				$str_conf = preg_replace('/(<virtualhost \*>\s*)/i', "$1ServerName $servername\n", $str_conf);
		}
		else
			$str_conf = preg_replace('/(\s*servername\s*.*)/i', "", $str_conf, 1, $count);
		*/

		$str_conf = preg_replace('/(\s*documentroot\s*)([^\s]*)/i', "$1$directory", $str_conf);

		$str_conf = preg_replace('/(\s*<directory )('.str_replace('/', '\/', $old_directory).')([\/ >]*.*?allow from )([^\s]*)/ism', '$1'.$directory.'$3all', $str_conf);

		file_put_contents( $apache2_siteconf, $str_conf );
		exec('/usr/bin/setfacl -R -x u:www-data '.$old_directory."\n");
		exec('/usr/bin/setfacl -R -x d:u:www-data '.$old_directory."\n");
		exec('/usr/bin/setfacl -R -m u:www-data:r-x '.$directory."\n");
		exec('/usr/bin/setfacl -R -m d:u:www-data:r-x '.$directory."\n");
		exec("/etc/init.d/apache2 restart &\n");
		info('start');
	}
    // Stäng av hemsida
	else if( !isset($_POST['server_active']) ) {
		require('stop.php');

		info('shutdown');
	}
	
}

////////////////////////////
////////////////////////////


switch( $_GET['t'] ) {
default:
case 'web':
	savebase();
	break;
}


?>
